/**
 *
 * 关卡场景基类
 * @author 
 *
 */
class GuankaBase extends egret.Sprite {
    public static instance: GuankaBase;
    /**地图位图*/
    public bm: egret.Bitmap;
    /**建造工具*/
    protected tool: BuildTool;
    
    //双方BOSS
    protected EnemyLife: number;
    protected FriendLife: number;
    //面板
    public board: egret.Bitmap;
    public label: egret.TextField;
    public lifetxt: egret.TextField;
    public damagetxt: egret.TextField;
    
    /**地基*/

    /**地基坐标数组*/
    public leftPoseArr: number[][];
    /**地基坐标数组*/
    protected rightPoseArr: number[][];

    /**防御塔集结点数组,对应地基的baseIdx*/
    protected soldPointArr: number[][];
    /**塔数组*/
    protected towerArr: any[];
    /**建造队列*/
    protected buildQuene: any[];
    /**显示对象层级排序数组*/
    public objArr: any[];
    
    /**友军数组*/
    public soldier: any[];
    public soldierInfo:any[];
    //敌军数组
    public enemy: any[];
    
    public shape: egret.Shape;
    
    /**地基层*/
    protected baseLayer: egret.Sprite;
    /**范围层*/
    protected areaLayer: egret.Sprite;
    /**怪物层、士兵层、英雄层、塔层(层级排序)*/
    public objLayer: egret.Sprite;
    /**弓箭、炮弹层*/
    public weaponLayer: egret.Sprite;
    /**工具层*/
    protected toolLayer: egret.Sprite;
    /**UI特效 提示层*/
    protected uiLayer: egret.Sprite;
    /**关卡UI对象*/
    public guankaUI: GuanKaUI;
    
    /**被选中地基x坐标*/
    protected curX: number;
    /**被选中地基y坐标*/
    protected curY: number;

    /**上一个选择的塔或则地基*/
    protected oldSelect:any;
    
    /**Gold*/
    public gold: number;
    /**Gold++*/
    public income: number;
    /**Life*/
    protected life: number;
    
    /**无尽模式累计波数*/
    protected rebuildPrice: number = 0;
    
    
    /**无尽模式难度累加系数*/
    protected perxs: number = 1;
    protected perxs2: number = 0.1;
    /**难度系数*/
    public hard: number = 1;
    
    /**总波数*/
    protected allBo: number = 1;
    /**当前波->指针*/
    public curBo: number = -1;
    /**敌人类别*/
    protected boType: string;
    /**当前波敌人生命*/
    protected boLife: number;
    /**当前波敌人速度*/
    protected boSpeed: number;
    /**当前波敌人攻击力*/
    protected boDamage: number;
    /**当前波敌人价值*/
    protected value: number;
    //敌人类型
    protected unitType: number;
    /**波进行中*/
    public boing: boolean = false;

    
    public otime: number = 0;
    public atime: number = 0;
    
    /**关卡时间记录*/
    protected stime: number = 0;
    protected mtime: number = 0;
    
    public timeGo: number = 0;
    
    /**怪物行走路径点数组*/
    protected roadArr: number[][][]=[];
    protected curRoadArr: number[][];
    
    /**所有波敌人数据 （类型、数量、生命、速度、攻击力、价值）*/
    public enemyData: any[][];
    
    protected talkSp:egret.Sprite = new egret.Sprite;
    protected talkBoard:egret.Bitmap;
    protected talkText: egret.TextField=new egret.TextField;
    
    //科技组
    public lifeUp:number = 0;
    public damagekUp: number = 0;
    public goldUp: number = 0;
    
    public confirmIcon: egret.Bitmap;
    
    public soldierArr:string[]=[];
    public rebuildSp: egret.Sprite = new egret.Sprite;
    public rebuildIcon:egret.Bitmap;
    public rebuildText: egret.TextField = new egret.TextField;

    
	public constructor() {
        super();
        GuankaBase.instance = this;
        //初始化各种数据
        this.towerArr = [];
        this.buildQuene = [];
        this.objArr = [];
        this.soldier = [];
        this.soldierInfo = [];
        this.enemy = [];
        this.soldierArr = [];
        //背景地图
        this.bm = new egret.Bitmap();
        this.addChild(this.bm);
        this.bm.touchEnabled = true;
        this.bm.addEventListener(egret.TouchEvent.TOUCH_BEGIN,this.bgMapClick,this);
        //地基层
        this.baseLayer = new egret.Sprite();
        this.addChild(this.baseLayer);
        //范围层
        this.areaLayer = new egret.Sprite();
        this.addChild(this.areaLayer);
        //怪物层、士兵层、英雄层、塔层(层级排序)
        this.objLayer = new egret.Sprite();
        this.addChild(this.objLayer);
        //添加武器层
        this.weaponLayer = new egret.Sprite();
        this.addChild(this.weaponLayer);
        //添加工具层
        this.toolLayer = new egret.Sprite();
        this.addChild(this.toolLayer);
        //添加UI层
        this.uiLayer = new egret.Sprite();
        this.addChild(this.uiLayer);

        this.showShape();
        
	}
	
    //================================
    /**背景地图被点击*/
    protected bgMapClick(e: egret.TouchEvent) {
        this.guankaUI.boardSp.visible = false;
        var icon = Group.selectedIcon
        if(icon!=null){
            if(icon.istouch==false) {
                if(e.stageX > 30 && e.stageX < 450 && e.stageY > 360 && e.stageY < 530) {
                    this.gold -= icon.price;
                    this.guankaUI.setGold(this.gold);                   
                    this.addSoldier(icon.res,e.stageX,e.stageY);
                    Group.disposeIcon();
                }
            }
        }
        var obj = Group.selectedItem;
        if(obj == null)
            return;
        var basename = egret.getQualifiedSuperclassName(obj);
        if(basename == "AttackArcherBase" || basename == "ShieldSoldierBase" || basename == "TowersBase" || basename == "MagicTowerBase" || basename == "ExploTowerBase") {
            this.hideTool(null);
        }
        Group.dispose();
    }
    //================================
    

    
    /**创造UI*/
    protected createUI(){
        this.guankaUI = new GuanKaUI(this.weaponLayer,this.objLayer);
        this.uiLayer.addChild(this.guankaUI);
        //侦听再次尝试、退出
        this.uiLayer.addEventListener(MainEvent.TRYAGAIN,this.tryAgainHandle,this);
        this.uiLayer.addEventListener(MainEvent.QUITGUANKA,this.quitHandle,this);
        
        //延迟多少s显示UI
        var that = this;
        TweenMax.delayedCall(1.2,function() {
            that.guankaUI.showUI();
        });

        
        this.uiLayer.addChild(this.talkSp);
        this.talkBoard = Utils.createBitmapByName("talk");
        this.talkSp.addChild(this.talkBoard);
        
        
        this.talkText.text = "";
        this.talkText.size = 20;
        this.talkText.textColor = 0xffff00;
        this.talkText.fontFamily = "Microsoft YaHei";
        this.talkText.x = 80;
        this.talkText.y = 65;
        this.talkSp.addChild(this.talkText);
        
        this.talkSp.anchorOffsetX = this.talkSp.width / 2;
        this.talkSp.x = egret.MainContext.instance.stage.stageWidth / 2;
        this.talkSp.y = 50
        this.talkSp.visible = false;
        
//        this.uiLayer.addChild(this.rebuildSp);
//        this.rebuildIcon = Utils.createBitmapByName("rebuild_png");
//        this.rebuildSp.addChild(this.rebuildIcon);
//        
//        this.rebuildText.text = "3452";
//        this.rebuildText.size = 15;
//        this.rebuildText.textColor = 0x00ff00;
//        this.rebuildText.fontFamily = "Helvetica";
//        this.rebuildText.strokeColor = 0x3c3c3c;
//        this.rebuildText.stroke = 1;
//        this.rebuildText.x = 21;
//        this.rebuildText.y = 38;
//        this.rebuildSp.addChild(this.rebuildText);
//        this.rebuildText.anchorOffsetX = this.rebuildText.width/2;
//        
//        this.rebuildSp.anchorOffsetX = this.rebuildSp.width;
//        this.rebuildSp.x = egret.MainContext.instance.stage.stageWidth-5;
//        this.rebuildSp.y = 400;
//        this.rebuildSp.visible = false;
//        this.rebuildSp.addEventListener(egret.TouchEvent.TOUCH_BEGIN,this.backup,this)
    }
    
	

    
    /**地基、塔 被点击*/
    protected baseOrTowerTouch(e:egret.TouchEvent){
        //鼠标互斥管理
        Group.selectItem(e.currentTarget);
    }
    
    /**出现建造工具*/
    protected showTool(e: TowerEvent) {
        this.guankaUI.boardSp.visible=false;
        var obj = e.currentTarget;
        this.oldSelect = obj;
        //建立建造工具
        this.tool = new BuildTool(e.obj,this.gold);

        this.tool.x = obj.x;
        this.tool.y = obj.y - 17;
        if(obj instanceof MagicMage01){
            this.tool.x+=5;
        }
        if(obj instanceof HumanTower) {
            this.tool.x += 10;
            this.tool.y -= 30;
        }
        this.toolLayer.addChild(this.tool);
        this.tool.anchorOffsetX = this.tool.width / 2;
        //侦听该工具选项被点击
        this.tool.addEventListener(ToolEvent.BUILD_START,this.buildStart,this);

    }
    
    public showShape(){
        this.shape = new egret.Shape();
        this.shape.graphics.beginFill(0xff0000,1);
        this.shape.graphics.drawRect(0,0,480,370);
        this.shape.graphics.endFill();
        this.shape.alpha=0;
        this.addChild(this.shape);    
    }

    public float(str: string,x: number,y: number,color:any=0x00EC00){
        var float:egret.TextField = new egret.TextField();
        //漂浮文字
        this.addChild(float);
        float.anchorOffsetX = float.width / 2;
        float.size = 13;
        float.textColor = color;
        float.text=str;
        float.x = x;
        float.y = y;
        TweenMax.to(float,2,{
            y: float.y - 50,alpha: 0 ,onComplete: function() {
                if(float.parent != null) {
                    float.parent.removeChild(float);
                }
            }});
    
    }
    
    /**隐藏建造工具*/
    public hideTool(e: TowerEvent) {
        this.guankaUI.boardSp.visible = false;
        //清除区域绘制
        while(this.areaLayer.numChildren > 0) {
            this.areaLayer.removeChildAt(0);
        }
        //清除建造工具
        if(this.tool == null)
            return;
        this.tool.removeEventListener(ToolEvent.BUILD_START,this.buildStart,this);
        this.tool.hide();
        this.tool = null;
    }
	
    /**开始建筑(修建 升级 sell)*/
    protected buildStart(e: ToolEvent) {
        //记录坐标
        this.curX = this.oldSelect.x;
        this.curY = this.oldSelect.y;

                
        //显示建造等待动画 若等于第一级则新建
        var name = e.className;
        if(name != "SellTower" && name != "gold" && name != "arrow" && name != "tower") {
            //修建动画
            var buildWait: BuildWait = new BuildWait(this.oldSelect.nameInfo);
            buildWait.x = this.curX;
            buildWait.y = this.curY;
            this.objLayer.addChild(buildWait);
            buildWait.addEventListener(ToolEvent.BUILD_COMP,this.buildComp,this);
            //减掉金钱e.price
            this.gold -= e.price;
            this.guankaUI.setGold(this.gold);
            //加入建造队列
            var obj: any = {};
            obj.className = e.className;
            obj.x = this.curX;
            obj.y = this.curY;

            this.buildQuene.push(obj);
            this.gold += TowerLevel.soldierData[this.oldSelect.nameInfo].price;
            this.guankaUI.setGold(this.gold);
        } else if(name == "SellTower") {//sell
            var towerName: string = this.oldSelect.nameInfo;
            //获得金钱(塔价格的三分之一)
            this.gold += TowerLevel.soldierData[towerName].price;
            this.guankaUI.setGold(this.gold);
            //console.log(this.gold);
            //卖掉音效
            SoundManager.playEffect("sell_tower");
        } else if(name == "LockTower") {//lock
            //锁定 do nothing
            //TIP 升级项目锁定了，攒到星星后前往升级面板解锁。
            
            return;
        } else if(name == "gold") {//lock
            this.goldUp++;
            this.gold -= e.price;
            this.guankaUI.setGold(this.gold);
            Group.dispose();
            this.hideTool(null);
            return;
        } else if(name == "arrow") {//lock
            this.damagekUp++;
            this.gold -= e.price;
            this.guankaUI.setGold(this.gold);
            Group.dispose();
            this.hideTool(null);
            return;
        } else if(name == "tower") {//lock
            this.lifeUp++;
            this.gold -= e.price;
            this.guankaUI.setGold(this.gold);
            Group.dispose();
            this.hideTool(null);
            return;
        }
                    
        //移除工具
        Group.dispose();
        this.hideTool(null);
                    
        //移除上一个塔 移除侦听 并从数组中删除
        this.oldSelect.removeEventListener(egret.TouchEvent.TOUCH_BEGIN,this.baseOrTowerTouch,this);
        if(egret.getQualifiedSuperclassName(this.oldSelect) != "Base") {//地基
            this.objLayer.removeChild(this.oldSelect);
            //从对象数组移除
            var index = this.objArr.indexOf(this.oldSelect);
            if(index != -1) {
                this.objArr.splice(index,1);
            }
            //从友军数组移除
            index = this.soldier.indexOf(this.oldSelect);
            if(index != -1) {
                this.soldier.splice(index,1);
            }
            //销毁塔以及内部对象
            this.oldSelect.hp=0;
            this.oldSelect.canClear = true;
        }
        this.oldSelect = null;
    }
        	
    /**升级完成*/
    protected buildComp(e: ToolEvent) {
        //从舞台删除升级动画
        var ta = e.currentTarget;
        ta.removeEventListener(ToolEvent.BUILD_COMP,this.buildComp,this);
        this.objLayer.removeChild(ta);
        ta = null;
        //反射 className
        var obj = this.buildQuene.shift();
        this.addSoldier(obj.className,obj.x,obj.y);       
    }
    
    public heroSound(sound:string,text:string,time:number = 700){

        this.talkText.text = text;
        this.talkText.anchorOffsetX = this.talkText.width / 2;
        this.talkText.anchorOffsetY = this.talkText.height / 2;
        this.talkSp.visible = true;
        this.talkSp.scaleX = 0.1;
        this.talkSp.scaleY = 0.1;
        egret.Tween.get(this.talkSp).to({ scaleX: 1,scaleY: 1 },200).wait(time).to({ visible:false});
        SoundManager.playEffect(sound);
        
    }
    
    /**实时刷新*/
    protected onEnterFrame(advancedTime: number) {
        this.timeGo+=advancedTime;
        if(this.otime < Math.floor(this.timeGo / 1000)){
            this.otime = Math.floor(this.timeGo / 1000);
            
            for(var i = 0;i < this.enemy.length;i++) {
                var enemy = this.enemy[i];
                if(enemy.hp > 0) {
                    //刷新敌人 数组
                    enemy.targets = this.soldier;
                }
            }
            
            this.stime+=1;
            this.gold+=this.goldUp;
            this.guankaUI.setGold(this.gold);
            if(this.atime >1) {
                this.atime--;
                if(this.atime == 10) {
                    this.heroSound("quick","快点吧，我等的\n花都谢了！",2500);
                }
            } else if(this.atime == 1&&!this.boing){
                this.atime--;
                this.attack();
                this.boing = true;
            }

            if(this.stime >= 60) {
                this.mtime++
                this.stime = 0;
            }
            
        this.guankaUI.setBos(this.mtime,this.stime,this.atime);
        
        }

        //判断敌人是否死亡或逃脱，更新敌人数组
        this.removeEnemies();
        //实时刷新本方塔
        //this.enterFrameTowers(advancedTime);
        //
        if(this.guankaUI)
            this.guankaUI.onEnterFrame(advancedTime);
        //实时刷新排序数组(根据y轴改变对象层级)
        this.objArr = Utils.sortarr(this.objArr);
        for(var i = 0;i < this.objArr.length;i++) {
            var obj = this.objArr[i];
            if(this.objLayer.contains(obj))
            this.objLayer.setChildIndex(obj,i);
        }

        
    }
    
    /**回收敌人*/
    protected removeEnemies() {
        var i: number;
        for(i = 0;i < this.enemy.length;i++) {
            var tar = this.enemy[i];
            if(tar.canClear) {
                if(tar.hp>0) {
                    this.FriendLife -=tar.price;                    
                }
                this.enemy.splice(i,1); 
            }
        }
        for(i = 0;i < this.soldier.length;i++) {
            var tar = this.soldier[i];
            if(tar.canClear) {
                if(tar.hp > 0) {
                    this.EnemyLife -= tar.price;
                }
                this.soldier.splice(i,1);
            }
        }
        if(this.enemy.length+this.soldier.length == 0&&this.boing){
            this.boing = false;
            this.allBo++;
            this.soldier=[];
            this.enemy=[];
            if(this.allBo>=5){
                this.gold = this.gold + 150;
            }else{
                this.gold = this.gold + 60 + this.allBo * 20;
            }

            if(this.curBo<this.enemyData.length-1){
                this.curBo++;
            }else{
                this.curBo = 0;
                this.hard++;
            }

            this.battle();
        }
        for(i = 0;i < this.objArr.length;i++) {
            var tar = this.objArr[i];
            if(tar.canClear) {
                this.objArr.splice(i,1);
            }
        }
    }
    
    public start(){
        this.atime = 120;
        this.createEnemies();
        this.guankaUI.setBos(this.mtime,this.stime,this.atime);
        this.guankaUI.rightSp.visible = true;
    }
    
    //就让好戏开场吧
    public battle(){
        var num:string = "";
        if(this.allBo<10){
            num = this.allBo.toString();           
        }else if(this.allBo==10){
            num="十"
        }else{
            num = "十" + this.allBo % 10
        }
        this.guankaUI.battle.text ="第"+num+"战";
        this.guankaUI.battleSp.alpha=1
        this.guankaUI.battle.anchorOffsetX = this.guankaUI.battle.width/2;
        egret.Tween.get(this.guankaUI.battleSp).wait(1500).call(this.createEnemies,this).to({ alpha: 0 },1500);

    }
    
    
    /**创建波*/
    protected createEnemies() {
//        if(this.curBo>0){
//            this.guankaUI.rightSp.visible = true;
//            if(this.rebuildPrice>0){
//                this.rebuildSp.visible = true;
//                this.rebuildText.text = this.rebuildPrice.toString();
//            }
//
//        }
        this.guankaUI.rightSp.visible = true;
        //等待或则创建敌人
        this.atime+=60;
        console.log("123");
        var num = Math.floor(Math.random() * this.enemyData[this.curBo].length);
        var thisEnemy = this.enemyData[this.curBo][num];
        for(var i = 0;i < thisEnemy["count"];i++){
            var posarr: number[][] = [this.leftPoseArr[i]];
            this.addEnemys(posarr,num);
        }
        num = Math.floor(Math.random() * this.enemyData[this.curBo].length);
        thisEnemy = this.enemyData[this.curBo][num];
        for(var i = 0;i < thisEnemy["count"];i++) {
            var posarr: number[][] = [this.rightPoseArr[i]];
            this.addEnemys(posarr,num);
        }
            
    }
            	
    /**产生敌人*/
    protected addEnemys(roadArr: number[][] = null,num:number) {

        var thisEnemy = this.enemyData[this.curBo][num];
        var attackType = thisEnemy["attackType"];
        if(attackType == 1) {
            var sp: any = <ShieldSoldier01>ObjectPool.getInstance().createObject(ShieldSoldier01);
        } else if(attackType == 2) {
            var sp: any = <AttackArcher01>ObjectPool.getInstance().createObject(AttackArcher01);
        } else {
            var sp: any = <MagicMage01>ObjectPool.getInstance().createObject(MagicMage01);
        }
        sp.init(roadArr,thisEnemy["life"],thisEnemy["damage"]);
        sp.addTexture(thisEnemy["type"],thisEnemy["info"]);

        sp.specialType = thisEnemy["specialType"];//获取特殊类型
        sp.fireDelay = thisEnemy["fireDelay"];//获取攻击速度
        sp._maxSpeed = thisEnemy["maxSpeed"];//获取攻击类型
        sp.price = thisEnemy["price"];//获取价值
        sp.minSoldRadius = thisEnemy["min"];;
        sp.value = thisEnemy["value"];
        this.objLayer.addChild(sp);
        this.objArr.push(sp);
        sp.targets = this.soldier;
        sp.camp = false;
        this.enemy.push(sp);
        sp.touchEnabled =true;
        sp.addEventListener(egret.TouchEvent.TOUCH_BEGIN,this.enemyInfo,this);     
    }
    protected enemyInfo(e: egret.TouchEvent){
        var obj = e.currentTarget;
        var board = this.guankaUI.boardSp;
        board.visible = true;
        //GuankaBase.instance.removeChild(board);
        this.guankaUI.label.text = "第" + (this.allBo ) + "波";
        this.guankaUI.type.text = "";
        this.guankaUI.info.text = obj.nameInfo;
        this.guankaUI.tip.text = "";
        this.guankaUI.lifetxt.text = obj.life;
        this.guankaUI.damagetxt.text = obj.damage;
        
        board.y = obj.y - 130; 
        if(e.stageX < 86) {
            board.x = 10;
        } else if(e.stageX>390){
            board.x = 300;
        }else{
            board.x = e.stageX-86;
        }
    
    }
    
//    
//    public backup(){
//        this.guankaUI.rightSp.visible = true;
////        this.rebuildSp.visible = false;
////        this.gold-=this.rebuildPrice;
////        this.guankaUI.setGold(this.gold);
////        this.rebuildPrice = 0;
//        for(var i =0;i<this.soldierInfo.length;i++){
//            this.addSoldier(this.soldierInfo[i]["name"],this.soldierInfo[i]["x"],this.soldierInfo[i]["y"])
//        }
//        this.soldierInfo = [];
//    }
    
    //创建军队
    public addSoldier(str:string,x:number,y:number) {
        var posarr: number[][];
        var attackType = TowerLevel.soldierData[str].attackType;//获取攻击类型
        if(attackType == 1) {
            var sp: any = <ShieldSoldier01>ObjectPool.getInstance().createObject(ShieldSoldier01);
        } else if(attackType == 2) {
            var sp: any = <AttackArcher01>ObjectPool.getInstance().createObject(AttackArcher01);
        } else {
            var sp: any = <MagicMage01>ObjectPool.getInstance().createObject(MagicMage01);
        }
        var soldierData = TowerLevel.soldierData[str];
        var res = soldierData.type;//获取特殊类型
        sp.addTexture(res,str);

        sp.specialType = soldierData.specialType;//获取特殊类型
        sp.unitType = soldierData.unitType;//获取单位类型
        sp.life = soldierData.life;//获取生命值
        sp.damage = soldierData.damage;//获取伤害
        sp.fireDelay = soldierData.fireDelay;//获取攻击速度
        sp._maxSpeed = soldierData.maxSpeed;//获取攻击类型
        sp.minSoldRadius = soldierData.min;
        sp.value = soldierData.value;
        sp.price = soldierData.price;
        //加入到引用对象
        this.objLayer.addChild(sp);
        this.objArr.push(sp);
        posarr=[[x-4,y+10]]
        sp.targets = this.enemy;
        sp.init(posarr,sp.life,sp.damage);
        sp.touchEnabled = true;
        sp.addEventListener(egret.TouchEvent.TOUCH_BEGIN,this.baseOrTowerTouch,this);
        sp.addEventListener(TowerEvent.SHOWTOOL,this.showTool,this);
        sp.addEventListener(TowerEvent.HIDETOOL,this.hideTool,this);
        sp.camp = true;
        this.soldier.push(sp);
    }
    
    public attack(){
        //波开始音效
        this.guankaUI.boardSp.visible = false;
        this.hideTool(null);
//        this.rebuildSp.visible = false;
//        this.rebuildPrice = 0;
        SoundManager.playEffect("bo_start");
        var numOne: number = 0
        var numTwo: number = 0;
        for(var i = 0;i < this.soldier.length;i++) {
            var obj = this.soldier[i];
            var posarr: number[][];
            this.soldierInfo[i] = { "name": obj.nameInfo,"x": obj.x + 4,"y": obj.y - 10 };
//            this.rebuildPrice += TowerLevel.soldierData[obj.nameInfo].price;
            obj.touchEnabled = false;
            obj.removeEventListener(egret.TouchEvent.TOUCH_BEGIN,this.baseOrTowerTouch,this);
            obj.removeEventListener(TowerEvent.SHOWTOOL,this.showTool,this);
            obj.removeEventListener(TowerEvent.HIDETOOL,this.hideTool,this);
            if(obj.specialType==13){
                this.addSoldier("s01_1",obj.x-30,obj.y+20)
                this.addSoldier("s01_1",obj.x + 30,obj.y + 20)
                this.addSoldier("s01_1",obj.x ,obj.y + 20)
            } else if(obj.specialType==14){
                this.addSoldier("s05_1",obj.x,obj.y + 40)
            }
            if(obj.x >= 240) {
                if(obj.x < 320) {
                    posarr = [[obj.x,obj.y],[320,360],[320,110],[240,60]];
                } else if(obj.x > 400) {
                    posarr = [[obj.x,obj.y],[400,360],[400,110],[240,60]];
                } else {
                    posarr = [[obj.x,obj.y],[obj.x,110],[240,60]];
                }
                numOne++;

            } else {

                if(obj.x < 80) {
                    posarr = [[obj.x,obj.y],[80,360],[80,110],[240,60]];
                } else if(obj.x > 160) {
                    posarr = [[obj.x,obj.y],[160,360],[160,110],[240,60]];
                } else {
                    posarr = [[obj.x,obj.y],[obj.x,110],[240,60]];
                }
                numTwo++;
            }
            obj.initRoad(posarr);
        }
        
        if(numOne < 1 || numTwo < 1) {
            this.heroSound("Thanks","谢谢你！");
        }
        
        for(var i = 0;i < this.enemy.length;i++) {
            var obj = this.enemy[i];
            var posarr: number[][];
            obj.touchEnabled = false;
            obj.removeEventListener(egret.TouchEvent.TOUCH_BEGIN,this.enemyInfo,this);
            if(obj.x >= 240) {
                posarr = [[obj.x,obj.y],[obj.x,500],[240,550]];
            } else {
                posarr = [[obj.x,obj.y],[obj.x,500],[240,550]];
            }
            obj.initRoad(posarr);
        }
    }
    public damage(obj:any,target:any,damage:number){
    //1：范围伤害；2：攻击增强；3：反伤；4：平摊伤害；5：百分比伤害；6：重伤；7：被攻击回血；8：致盲；9：自爆；10：狂暴；11：格挡；12：范围法术
        var realDamage:number;
        var allDamage:number=0;
        
        if(obj.blind > 0) {
            var r: number = Math.random();
            if(r < 0.3) {
                this.float("miss",obj.x,obj.y - 60,0xff0000);
                return;
            }
        }
        realDamage = damage;
        
        if(target.specialType ==11) {
            var r: number = Math.random();
            if(r < target.value) {
                this.float("格挡",target.x,target.y - 60,0xff0000);
                obj.hp-=target.damage;
                var str:string = "-"+target.damage.toString();
                this.float(str,obj.x,obj.y - 60,0xff0000);
                return;
            }
        }
        //军刀 平摊伤害
        var allTargets:any[]=[];
        if(obj.specialType == 4) {
            for(var i: number = 0;i < obj.targets.length;i++) {
                if(Math.abs(obj.targets[i].x - target.x) < 30 && Math.abs(obj.targets[i].y - target.y) < 30) {
                    allTargets.push(obj.targets[i])
                }
            }

            for(var n: number = 0;n < allTargets.length;n++) {
                allTargets[n].hp -= realDamage / allTargets.length;
            }
            
        }else{
            target.hp -= realDamage;
        }

        
        allDamage += realDamage;

        //范围伤害
        if(obj.specialType == 1) {
            for(var i: number = 0;i < obj.targets.length;i++) {
                if(Math.abs(obj.targets[i].x - obj.target.x) < 50 && Math.abs(obj.targets[i].y - obj.target.y) < 50 && obj.targets[i] != obj.target) {
                    obj.targets[i].hp -= obj.damage;
                    allDamage += obj.damage;
                }
            }
        }
        
        //愈战愈勇
        if(obj.specialType == 2) {
            obj.damage += obj.damage*obj.value;
        }
        //反伤
        if(target.specialType == 3) {
            obj.hp-= damage*0.3;
        }

        
        //额外造成10%伤害
        if(obj.specialType == 5) {
            target.hp -= target.life * 0.1;
        }
        

        //重伤
        if(obj.specialType == 6&&target.hp/target.life<0.5){
            target.hp-=realDamage*2;
        }
        //恢复
        if(target.specialType == 7) {
            target.hp+=5;
        }
        //致盲
        if(obj.specialType == 8) {
            target.blind =1;
        }
        
        //吸血
        if(obj.suckBlood > 0) {
            obj.hp += Math.floor(allDamage * obj.suckBlood);
        }
    }
    
//    /**实时刷新本方塔*/
//    protected enterFrameTowers(advancedTime: number) {
//        var len = this.towerArr.length;
//        var obj: any;
//        for(var i = 0;i < len;i++) {
//            obj = this.towerArr[i];
//            obj.onEnterFrame(advancedTime);
//        }
//    }
    
    /**退出关卡*/
    protected quitHandle(e: MainEvent) {
        //打开loader界面加载地图界面
        Main.instance.dispatchEvent(new MainEvent(MainEvent.OPENLOADBAR,"maps"));
    }
    
    /**再次尝试*/
    protected tryAgainHandle(e: MainEvent) {}
    
    /**关卡胜利*/
    protected victory() {
        this.clear();
        this.guankaUI.showVictory();
        //更新关卡通关数据、塔升级数据
        StorageSetting.setGuankaPass(Main.curIdx);
        StorageSetting.setTowerUpgrade(Main.curIdx);
    }
            
    /**关卡失败*/
    protected lose() {
        this.clear();
        this.guankaUI.showLose();
        //更新关卡数据
        //if(Main.wujin){
            //StorageSetting.setGuankaWujin(Main.curIdx,this.boSum+this.curBo);
        //}
    }
                
    /**清除*/
    public pause() {
        egret.Ticker.getInstance().unregister(this.onEnterFrame,this);
    }
    public clear() {
        //停止背景音乐
        SoundManager.stopBgSound();
        //暂停心跳控制器
        egret.Ticker.getInstance().unregister(this.onEnterFrame,this);
        //清空对象池
        ObjectPool.getInstance().destroyAllObject();
    }
    
    /**销毁关卡*/
    public destroy(){
        this.roadArr = null;
        this.curRoadArr = null;
        this.leftPoseArr = null;
        this.rightPoseArr = null;
        this.enemyData = null;
        this.towerArr = null;
        this.objArr = null;
        this.enemy = null;
        this.soldier= null;
        this.soldierArr = null;
        //关闭心跳控制器
        //销毁对象池
        egret.Tween.removeAllTweens();
        ObjectPool.getInstance()._pool = {};
        //删除UI
        
    }

}
